<template>
  <div id="map" class="map-container">
    <div class="map-controls">
      <div class="base-layer-switcher">
        <button :class="['control-btn', activeBaseLayer === 'vector' ? 'active' : '']"
          @click="switchTiandituBaseLayer('vector')">
          矢量图
        </button>
        <button :class="['control-btn', activeBaseLayer === 'image' ? 'active' : '']"
          @click="switchTiandituBaseLayer('image')">
          影像图
        </button>
      </div>
    </div>
    <MapPopup :map-box="map" v-show="popupVisible" :feature-data="popupFeatureData" :layer-id="popupLayerId"
      :position="popupPosition" @close="closePopup" />

    <!-- 右侧弹窗面板 -->
    <RightPanel :visible="panelVisible" :title="panelTitle" :panel-layers="activePanelLayers"
      :active-layer-id="activePanelLayer" @close="closePanel" @switch-layer="switchPanelLayer">
      <WaterQualityPanel v-if="activePanelLayer === 'zidongzhan'" />
      <ShougongduanmianPanel v-if="activePanelLayer === 'shougongduanmian'" />
      <PollutionSourcePanel v-if="activePanelLayer === 'wuranyuan'" />
      <shuiyuandiPanel v-if="activePanelLayer === 'shuiyuandi'" />
      <RehupaiwukouPanel v-if="activePanelLayer === 'ruhepaiwukou'" />
      <yujingPanel ref="yujingPanelRef" v-if="activePanelLayer === 'yujing'" @showPointDetails="showPointDetails"
        @queryYujingData="queryYujingData" />
    </RightPanel>
  </div>
</template>

<script>
import 'ol/ol.css';

import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import { XYZ } from 'ol/source';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { defaults as defaultControls, ScaleLine } from 'ol/control';
import { singleClick } from 'ol/events/condition';
import Select from 'ol/interaction/Select';
import { getCenter } from 'ol/extent';
import 'ol/proj/epsg4326';

import { wmsBaseUrl } from '@/views/biz/utils/config';
import {
  createPointLayer,
  createHeatmapLayer,
  createWmsLayer,
  removeLayerById,
  loadGeoJsonLayer,
} from '@/views/biz/utils/layerLoader';
import { getData } from '@/views/biz/utils/getData';

import MapPopup from './MapPopup.vue';
import RightPanel from './RightPanel.vue';
import WaterQualityPanel from './panel/WaterQualityPanel.vue';
import ShougongduanmianPanel from './panel/ShougongduanmianPanel.vue';
import PollutionSourcePanel from './panel/PollutionSourcePanel.vue';
import shuiyuandiPanel from './panel/shuiyuandiPanel.vue';
import RehupaiwukouPanel from './panel/RehupaiwukouPanel.vue';
import yujingPanel from './panel/yujingPanel.vue';

export default {
  name: 'MapContainer',
  components: {
    MapPopup,
    RightPanel,
    WaterQualityPanel,
    ShougongduanmianPanel,
    PollutionSourcePanel,
    shuiyuandiPanel,
    RehupaiwukouPanel,
    yujingPanel
  },

  data() {
    return {
      map: null,
      mapOverlay: null,
      tiandituToken: '3d9e801ed2c10bc2e6eba8037e53817b',
      loadedLayers: {},
      currentLayerIds: [],
      // 弹窗相关数据
      popupVisible: false,
      popupFeatureData: {},
      popupLayerId: '',
      popupPosition: [0, 0],
      // 右侧面板相关数据
      panelVisible: false,
      panelTitle: '图层信息',
      activePanelLayer: '',
      activePanelLayers: [],
      activeBaseLayer: 'vector' // 'vector' 或 'image'
    };
  },
  computed: {
    // 判断当前是否应该显示水质面板（多个自动站图层共用）
    isWaterQualityPanel() {
      const waterQualityLayerIds = ['guokongzhan', 'shengkongzhan', 'shikongzhan', 'xiankongzhan', 'shougongduanmian'];
      return waterQualityLayerIds.includes(this.activePanelLayer);
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() { this.map?.dispose(); },
  methods: {

    navigateToMap() {
      this.$router.push('/jiashicang');
    },
     showPointDetails(point) {
      if (!point.longitude || !point.latitude) {
        this.$notify.error({
          title: '错误',
          message: '点位坐标无效',
          duration: 2000
        });
        return;
      }
      let coordinate = [point.longitude, point.latitude]
      this.map.getView().setCenter(coordinate);
    },
    initMap() {
      let base_layer = createWmsLayer({
        url: wmsBaseUrl,
        layerName: 'gp:base_dlg',
        layerId: 'base_dlg',
        params: {
          "format": 'image/png',
          'VERSION': '1.1.1',
          "STYLES": '',
          "LAYERS": 'gp:base_dlg',
        }
      });
      base_layer.set("id", 'base_dlg');
      base_layer.setVisible(true);
      let base_img = createWmsLayer({
        url: wmsBaseUrl,
        layerName: 'gp:base_img',
        layerId: 'base_img',
        params: {
          "format": 'image/png',
          'VERSION': '1.1.1',
          "STYLES": '',
          "LAYERS": 'gp:base_img',
        }
      });
      base_img.set("id", 'base_img');
      base_img.setVisible(false);

      const tileGrid = new WMTSTileGrid({
        origin: [-180, 90],
        resolutions: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625],
        matrixIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
      })
      //tainditu影像
      let tianditu_img = new TileLayer({
        name: 'tianditu-img',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
          projection: 'EPSG:4326',
          tileGrid: tileGrid
        })
      })
      tianditu_img.set("id", 'base_tianditu_img');
      tianditu_img.setVisible(false);
      let tianditu_cia = new TileLayer({
        name: 'tianditu-cia',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
          projection: 'EPSG:4326',
          tileGrid: tileGrid
        })
      })
      tianditu_cia.set("id", 'base_tianditu_cia');
      tianditu_cia.setVisible(false);
      //tainditu矢量
      let tianditu_vec = new TileLayer({
        name: 'tianditu-vec',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
          projection: 'EPSG:4326',
          tileGrid: tileGrid
        })
      })
      tianditu_vec.set("id", 'base_tianditu_vec');
      tianditu_vec.setVisible(true);
      let tianditu_cva = new TileLayer({
        name: 'tianditu-cva',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.tiandituToken}`,
          projection: 'EPSG:4326',
          tileGrid: tileGrid
        })
      })
      tianditu_cva.set("id", 'base_tianditu_cva');
      tianditu_vec.setVisible(true);
      this.map = new Map({
        target: 'map',
        // 通过 defaultControls 关闭缩放控件 (zoom)
        // 如需保留刻度尺，可用 .extend([new ScaleLine()]) 添加
        controls: defaultControls({ zoom: false }),
        layers: [
          tianditu_vec,
          tianditu_cva,
          tianditu_img,
          tianditu_cia,
          base_layer,
          base_img
        ],
        view: new View({
          projection: 'EPSG:4326',
          // center: [112.930691, 35.791355],
          center: [113.04445370850065, 35.78913816364938],
          constrainResolution: true,
          zoom: 11,
          maxZoom: 18,
          minZoom: 1
        })
      });
      this.map.getView().on('change:center', (evt) => {
        const center = this.map.getView().getCenter();
        console.log('地图已平移，新中心点:', center);
      });

      //  this.map.addLayer(base_layer);
      //  let region_promise= loadGeoJsonLayer({
      //       data: '/geojson/140581.geojson',
      //       layerId: 'base_region',
      //       projection: 'EPSG:4326'
      //     });
      //     let river_promise= loadGeoJsonLayer({
      //       data: '/geojson/river.geojson',
      //       layerId: 'base_river',
      //       projection: 'EPSG:4326'
      //     });
      //     Promise.all([region_promise, river_promise])
      //   .then(([regionLayer, riverLayer]) => {


      //     // 添加到地图
      //     this.map.addLayer(regionLayer);
      //     this.map.addLayer(riverLayer);

      //     // 保存引用
      //     this.loadedLayers['base_region'] = regionLayer;
      //     this.loadedLayers['base_river'] = riverLayer;
      //   })
      //   .catch(error => {
      //     this.$message.error('基础地图数据加载失败');
      //     console.error('GeoJSON图层加载错误:', error);
      //   });
      // 添加点击交互
      this.registerMapClick();
    },
    clickpointhandel(feature) {
      const layerId = feature ? feature['layerId'] : '';
      if (layerId === 'yujing') {
        this.$refs.yujingPanelRef.handleTab('detail', feature['pointId'], feature['pointName'])
      }
    },
    registerMapClick() {
      this.map.on('singleclick', (evt) => {
        const coordinate = evt.coordinate;
        const features = [];
        this.map.forEachFeatureAtPixel(evt.pixel, (feature) => {
          features.push(feature);
        });

        // 如果找到了要素，则可以进一步处理
        if (features.length > 0) {
          // 处理获取到的要素
          const feature = features[0];
          // 获取要素属性
          const featureData = feature.getProperties();
          this.clickpointhandel(featureData);

          // 获取图层信息
          const layerId = feature ? feature.get('layerId') : '';



          // 计算弹窗位置
          // const geometry = feature.getGeometry();
          // const coordinate = geometry.getType() === 'Point'
          //   ? geometry.getCoordinates()
          //   : getCenter(geometry.getExtent());

          // const pixel = this.map.getPixelFromCoordinate(coordinate);

          // 显示弹窗
          this.showPopup(featureData, layerId, coordinate);
        } else {

          this.closePopup();
        }
      });
    },

    addMapInteractions() {
      // 创建选择交互
      const selectInteraction = new Select({
        condition: singleClick,
        layers: (layer) => {
          // 只对矢量图层进行选择
          return layer instanceof VectorLayer;
        }
      });

      // 监听选择事件
      selectInteraction.on('select', (event) => {

        const selected = event.selected;
        if (selected.length > 0) {
          const feature = selected[0];
          // 获取要素属性
          const featureData = feature.getProperties();
          //console.log("featureData", featureData);

          // 获取图层信息
          const layerId = feature ? feature.get('layerId') : '';


          // 计算弹窗位置
          const geometry = feature.getGeometry();
          const coordinate = geometry.getType() === 'Point'
            ? geometry.getCoordinates()
            : getCenter(geometry.getExtent());

          // const pixel = this.map.getPixelFromCoordinate(coordinate);

          // 显示弹窗
          this.showPopup(featureData, layerId, coordinate);
        } else {
          this.closePopup();
        }
      });

      this.map.addInteraction(selectInteraction);
    },
    /**
     * 更新地图图层
     * 
     * @param {Array} newLayers - 新的图层组数组，每个图层组包含图层信息
     *        每个图层对象应包含id等属性
     */
    updateLayers(newLayers, currentActiveLayer) {
      // 提取所有新图层的ID
      const newLayerIds = [];
      newLayers.forEach(layerGroup => {
        if (layerGroup.layers && Array.isArray(layerGroup.layers)) {
          layerGroup.layers.forEach(layer => {
            newLayerIds.push(layer.id);
          });
        }
      });

      // 移除不再需要的图层
      this.currentLayerIds.filter(id => !newLayerIds.includes(id))
        .forEach(id => this.removeLayer(id));

      // 添加新图层
      const addLayerPromises = [];
      newLayers.forEach(layerGroup => {
        if (layerGroup.layers && Array.isArray(layerGroup.layers)) {
          layerGroup.layers.forEach(layer => {
            if (!this.currentLayerIds.includes(layer.id)) {
              this.currentLayerIds.push(layer.id);
              const promise = this.createLayer(layer).then((newLayer) => {
                if (newLayer) {
                  this.addLayerToMap(newLayer, { ...layer });
                }
              }).catch((error) => {
                console.error(`添加图层 ${layer.id} 失败:`, error);

              });
              addLayerPromises.push(promise);
            }
          });
        }
      });

      // 等待所有图层添加完成后处理面板显示逻辑
      Promise.all(addLayerPromises).then(() => {
        this.handlePanelVisibility(newLayers, currentActiveLayer);
      }).catch((error) => {
        console.error('添加图层过程中出现错误:', error);
        this.handlePanelVisibility(newLayers, currentActiveLayer);
      });
    },

    handlePanelVisibility(layers, currentActiveLayer) {
      const panelLayers = [];
      layers.forEach(layer => {
        let panelLayer = {};
        if (layer.id === 'guokongzhan' || layer.id === 'shengkongzhan' || layer.id === 'shikongzhan' || layer.id === 'xiankongzhan') {
          if (!panelLayers.some(item => item.id === 'zidongzhan')) {
            panelLayer = { "id": "zidongzhan", "name": "自动站" };
            panelLayers.push(panelLayer);
          }
        }
        else if (layer.id === 'qushuikou' || layer.id === 'shuiyuandiStation') {
          if (!panelLayers.some(item => item.id === 'shuiyuandi' || item.id === 'shuiyuandi')) {
            panelLayer = { "id": "shuiyuandi", "name": "水源地" };
            panelLayers.push(panelLayer);
          }
        }
        else {
          if (!panelLayers.some(item => item.id === layer.id)) {
            panelLayer = { "id": layer.id, "name": layer.name };
            panelLayers.push(panelLayer);
          }
        }
        // }
      });
      // 更新激活的面板图层数组
      this.activePanelLayers = panelLayers;

      if (panelLayers.length > 0) {
        console.log("panelLayers", panelLayers);
        this.activePanelLayer = currentActiveLayer.id;
        if (!this.activePanelLayer || !panelLayers.some(l => l.id === this.activePanelLayer)) {
          const activeLayer = panelLayers[panelLayers.length - 1];
          this.activePanelLayer = activeLayer.id;
          this.panelTitle = activeLayer.name + '信息';
        } else {
          // 确保panelTitle与当前activePanelLayer保持一致
          const currentLayer = panelLayers.find(l => l.id === this.activePanelLayer);
          if (currentLayer) {
            this.panelTitle = currentLayer.name + '信息';
          }
        }
        this.panelVisible = true;
      } else {
        this.panelVisible = false;
        this.activePanelLayer = '';
      }
    },


    // 切换面板图层
    switchPanelLayer(layer) {
      this.activePanelLayer = layer.id;
      this.panelTitle = layer.name;
    },

    // helper: 根据 id 查找地图图层
    getLayerById(id) {
      return this.map && this.map.getLayers().getArray().find(l => l.get('id') === id);
    },

    // 判断图层是否需要显示面板
    shouldShowPanel(layerId) {
      const panelLayerIds = ['zidongzhan', 'wuranyuan'];
      return panelLayerIds.includes(layerId);
    },
    createLayer(layer) {
      return new Promise((resolve, reject) => {
        let newLayer;
        switch (layer.dataType) {
          case 'dataApi':
            getData(layer.id)
              .then(response => {
                const data = response.data || [];
                if ('heatmap' in layer && layer.heatmap) {
                  newLayer = createHeatmapLayer({
                    data: data,
                    layerId: layer.id,
                    layerType: layer.geoType
                  });
                }
                else {
                  newLayer = createPointLayer({
                    data: data,
                    layerId: layer.id,
                    layerType: layer.geoType
                  });
                }
                resolve(newLayer);
              })
              .catch(error => {
                console.error(`获取图层 ${layer.id} 数据失败:`, error);
                reject(error);
              });
            break;
          case 'wms':
            try {
              newLayer = createWmsLayer({
                url: layer.layerUrl,
                layerName: layer.wmsLayerName,
                layerId: layer.id,
                params: layer.params || {}
              });
              resolve(newLayer);
            } catch (error) {
              console.error(`创建WMS图层 ${layer.id} 失败:`, error);
              reject(new Error(`创建WMS图层失败: ${error.message}`));
            }
            break;
          case 'wmts':
            // 实现面图层创建逻辑
            console.warn('wmts图层功能尚未实现');
            reject(new Error('wmts图层功能尚未实现'));
            break;
          case 'base':
            this.switchBaseLayer(layer);
            resolve(null);
            break;
          default:
            console.error('未知图层类型:', layer.type);
            reject(new Error(`未知图层类型: ${layer.type}`));
            break;
        }
      });
    },
    addLayerToMap(newLayer, layerConfig) {
      newLayer.set('id', layerConfig.id);
      newLayer.set('name', layerConfig.name);
      newLayer.set('type', layerConfig.geoType);
      if ('minZoom' in layerConfig && layerConfig.minZoom) {
        //console.log("minZoom", layerConfig.minZoom)
        newLayer.setMinZoom(layerConfig.minZoom);
      }
      if ('maxZoom' in layerConfig && layerConfig.maxZoom) {
        newLayer.setMaxZoom(layerConfig.maxZoom);
      }
      this.map.addLayer(newLayer);
      this.loadedLayers[layerConfig.id] = newLayer;
    },

    removeLayer(layerId) {
      this.currentLayerIds = this.currentLayerIds.filter(id => id !== layerId);
      if (this.loadedLayers[layerId]) {
        this.map.removeLayer(this.loadedLayers[layerId]);
        delete this.loadedLayers[layerId];
      }
    },
    switchBaseLayer(layer) {
      const baseLayers = ['tianditu-vec', 'tianditu-img'];
      baseLayers.forEach(layerId => {
        const mapLayer = this.map.getLayers().getArray().find(l => l.get('name') === layerId);
        if (mapLayer) mapLayer.setVisible(layerId === layer.id);
      });
    },

    // 弹窗相关方法
    showPopup(featureData, layerId, position) {

      this.popupFeatureData = featureData;
      this.popupLayerId = layerId;
      // this.popupLayerType = layerType;
      this.popupPosition = position;
      this.popupVisible = true;
    },

    closePopup() {

      this.popupFeatureData = {};
      this.popupLayerId = '';
      this.popupLayerType = '';
      this.popupVisible = false;
    },

    // 面板相关方法
    closePanel() {
      this.panelVisible = false;
      this.activePanelLayer = '';
      this.panelTitle = '图层信息';
      this.activePanelLayers = [];
    },
    queryYujingData(dateRange) {
      //console.log("queryYujingData", dateRange)
      getData('yujing', dateRange)
        .then(response => {
          const data = response.data || [];
          removeLayerById(this.map, 'yujing');
          let newLayer = createPointLayer({
            data: data,
            layerId: 'yujing',
            layerType: 'Point'
          });
          this.addLayerToMap(newLayer, {
            id: 'yujing',
            name: 'yujing',
            type: 'Point',
          });
        })
        .catch(error => {
          console.error(`获取预警数据失败:`, error);
        });
    },
    // 切换天地图底图类型（精简实现）
    switchTiandituBaseLayer(type) {
      this.activeBaseLayer = type;
      const ids = {
        vec: 'base_tianditu_vec',
        cva: 'base_tianditu_cva',
        img: 'base_tianditu_img',
        cia: 'base_tianditu_cia',
        base_img: 'base_img',
        base_dlg: 'base_dlg',
      };

      const setVisible = (id, visible) => {
        const layer = this.getLayerById(id);
        if (layer) layer.setVisible(visible);
      };

      if (type === 'image') {
        // 影像图：显示影像和影像注记，隐藏矢量相关图层
        setVisible(ids.vec, false);
        setVisible(ids.cva, false);
        setVisible(ids.img, true);
        setVisible(ids.cia, true);
        setVisible(ids.base_dlg, false);
        setVisible(ids.base_img, true);
      } else {
        // 矢量图（默认）
        setVisible(ids.vec, true);
        setVisible(ids.cva, true);
        setVisible(ids.img, false);
        setVisible(ids.cia, false);
        setVisible(ids.base_dlg, true);
        setVisible(ids.base_img, false);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
@import "~@/style/variables.scss";

.map-container {
  width: 100%;
  height: calc(100vh - 105px);
}

.map-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 1000;
}

.base-layer-switcher {
  display: flex;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);

  .control-btn {
    padding: 6px 12px;
    margin: 0;
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 12px;
    border-radius: 2px;
    transition: all 0.3s;

    &:hover {
      background: rgba(0, 0, 0, 0.1);
    }

    &.active {
      background: $base-blue-background; // reuse project variable
      color: white;
    }
  }
}
</style>